package PrjHttpUtils

/*
 * 当心被批处理清理
 */

import (
	"dgo/MyProj/PrjDBUtils"
	db_utils "dgo/goutils/db-utils"
	"dgo/goutils/utils"
	"fmt"
	"strings"
	"time"
)

var (
	LOG_DB_ID                 string                             = "main"
	LOG_DB_TableNameFunc      func(appid, apptype string) string = nil
	LOG_DB_CREATE_TABLE_TEMPL                                    = `
		CREATE TABLE $rep_table$ (
			fid  bigint NOT NULL AUTO_INCREMENT ,
			ftime datetime NULL ,
			fappid  varchar(30) NULL ,
			flvl  varchar(10) NULL ,        
			fmsgtype  varchar(20) NULL ,
			fmsg  text NULL ,
			fsrc  varchar(80) NULL ,
            ffromaddr varchar(80) NULL ,
			PRIMARY KEY (fid),
			INDEX idx_ftime (ftime) ,
			INDEX idx_fmsgtype (fmsgtype)
		);
	`
)

/*
time(unixHex),type,lvl,src,msg(jsonescape)\r\n
*/
func ProcessLog2DB(appid, apptype, fromaddr string, logbody string) (int, error) {
	lines := strings.Split(logbody, "\n")
	if len(lines) == 0 {
		return 0, nil
	}

	var strTable = ""
	if LOG_DB_TableNameFunc != nil {
		strTable = LOG_DB_TableNameFunc(appid, apptype)
	}
	if len(strTable) == 0 {
		strTable = fmt.Sprintf("log_%s_%s", apptype, time.Now().Format("200601"))
		err := PrjDBUtils.CheckCreateTableByID(LOG_DB_ID, strTable, LOG_DB_CREATE_TABLE_TEMPL)
		if err != nil {
			//fmt.Fprintf(os.Stderr, "创建日志数据表[%s]出现异常:%s", strTable, err.Error())
			return -1, err
		}
	}

	var lvsqls []string
	var recB = db_utils.NewRecUpdateUpbuilder()
	for i := 0; i < len(lines); i++ {
		str := utils.Trim(lines[i])
		if len(str) == 0 {
			continue
		}
		strmsgs := strings.SplitN(str, ",", 5)
		if len(strmsgs) != 5 {
			continue
		}
		// time(unixHex),type,lvl,src,msg(jsonescape)\r\n
		recB.Clear()
		recB.SetValue("ftime", utils.HexToDateTime(strmsgs[0], time.Now()))
		recB.SetValue("fappid", appid)
		recB.SetValue("fmsgtype", strmsgs[1])
		recB.SetValue("flvl", strmsgs[2])
		recB.SetValue("fsrc", strmsgs[3])
		recB.SetValue("fmsg", utils.ParserJsonEscapeStr(strmsgs[4]))
		recB.SetValue("ffromaddr", fromaddr)
		sql := recB.BuildInsert(strTable)
		lvsqls = append(lvsqls, sql)
	}
	r, _, err := PrjDBUtils.ExecuteBatchSQL(LOG_DB_ID, lvsqls...)
	return int(r), err

}
